package com.shenmawl.common.utils.mqtt;

import com.shenmawl.common.core.domain.AjaxResult;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MqttPushClient {
    private static final Logger logger = LoggerFactory.getLogger(MqttPushClient.class);

    @Autowired
    private PushCallback pushCallback;

    private static MqttClient client;

    private static MqttClient getClient() {
        return client;
    }

    private static void setClient(MqttClient client) {
        MqttPushClient.client = client;
    }

    public void connect(String host, String clientID, String username, String password, int timeout, int keepalive) {
        try {
            client = new MqttClient(host, clientID, new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            options.setConnectionTimeout(timeout);
            options.setKeepAliveInterval(keepalive);
            setClient(client);
            client.setCallback(pushCallback);
            client.connect(options);
        } catch (Exception e) {
            logger.error("MQTT connection failed", e);
        }
    }

    public AjaxResult publish(int qos, boolean retained, String topic, String pushMessage) {
        try {
            MqttMessage message = new MqttMessage();
            message.setQos(qos);
            message.setRetained(retained);
            message.setPayload(pushMessage.getBytes());
            MqttTopic mTopic = getClient().getTopic(topic);
            if (mTopic == null) {
                logger.error("Topic not exist");
                return AjaxResult.error("Topic not exist");
            }
            MqttDeliveryToken token = mTopic.publish(message);
            token.waitForCompletion();
            return AjaxResult.success();
        } catch (MqttException e) {
            logger.error("MQTT publish failed", e);
            return AjaxResult.error();
        }
    }

    public void subscribe(String topic, int qos) {
        try {
            getClient().subscribe(topic, qos);
        } catch (MqttException e) {
            logger.error("MQTT subscription failed", e);
        }
    }
}
